package com.stark.wechat.service.menu.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.stark.wechat.util.JacksonUtils;

import java.io.IOException;

/**
 * {@link Button} 序列化模块
 *
 * @author <a href="mengbin@eastsoft.com.cn">Ben</a>
 * @version 1.0.0
 * @since 2025/8/6
 */
public class ButtonModule extends SimpleModule {

    private static final long serialVersionUID = -2827938784904965439L;

    public ButtonModule() {
        addDeserializer(Button.class, new ButtonDeserializer());
    }

    public static class ButtonDeserializer extends JsonDeserializer<Button> {

        @Override
        public Button deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            JsonNode root = p.getCodec().readTree(p);
            if (root.has("type")) {
                String type = root.get("type").asText();
                ButtonType buttonType = ButtonType.valueOf(type);
                return JacksonUtils.deserialize(root.toPrettyString(), buttonType.getButtonClass());
            }

            ParentButton parentButton = new ParentButton(root.get("name").asText());
            JsonNode subButtonNode = root.get("sub_button");
            // 兼容【查询自定义菜单信息】接口返回中 sub_button 下多一级 list 的场景：https://developers.weixin.qq.com/doc/service/api/custommenu/api_getcurrentselfmenuinfo.html#_5-2-API%E8%AE%BE%E7%BD%AE%E8%8F%9C%E5%8D%95%E7%A4%BA%E4%BE%8B
            if (subButtonNode.isObject() && subButtonNode.has("list")) {
                subButtonNode = subButtonNode.get("list");
            }
            subButtonNode.forEach(node -> {
                String type = node.get("type").asText();
                ButtonType buttonType = ButtonType.valueOf(type);
                Button subButton = JacksonUtils.deserialize(node.toPrettyString(), buttonType.getButtonClass());
                parentButton.addSubButton(subButton);
            });
            return parentButton;
        }

    }

}
